<template>
    <g-table-page
        :store-model-name="storeModelName"
        add-btn-link="/monitor/job/add"
        add-btn-link-text="添加定时任务"
        :selection="false"
        :table-operation="tableOperation"
        :show-dropdown-groups="true"
    >
        <!-- 根据tableHeadList slotName字端 动态插入 插槽 -->
        <template v-for="item in tableHeadListSlotName" :key="item.slotName" #[item.slotName]="{ row }">
            <div v-if="row">
                <span v-if="item.prop == 'runing'">
                    <el-switch
                        v-model="row['runing']"
                        class="ml-2"
                        inline-prompt
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        active-value="0"
                        inactive-value="1"
                        active-text="运行中"
                        inactive-text="已停用"
                        @change="changeStatusFunc(row)"
                    />
                </span>
            </div>
        </template>
    </g-table-page>
    <g-dialog
        v-model:dialog-visible="logVisible"
        :title="logTitle"
        :width="'1200px'"
        :show-cancel-btn="false"
    >
        <el-table
            ref="logTableRef"
            :data="logData"
            :default-sort="{ prop: 'jobLogId', order: 'desc' }"
            style="width: 100%"
            max-height="500"
        >
            <el-table-column
                v-for="item in logTableHeadList"
                :key="item.prop"
                :min-width="item.width ? item.width : item.label.length * 14 + 44"
                show-overflow-tooltip
                :sortable="item.sortable ? item.sortable : false"
                :prop="item.prop"
                :label="item.label"
            >
                <template #default="scope">
                    <div v-if="item.prop == 'status'">
                        <div v-if="scope.row">
                            <span v-if="item.prop == 'status'">
                                <el-tag
                                    v-if="scope.row['status'] == '0'"
                                    :key="scope.row['status']"
                                    type="success"
                                    effect="light"
                                    round
                                >
                                    正常
                                </el-tag>
                                <el-tag
                                    v-if="scope.row['status'] == '1'"
                                    :key="scope.row['status']"
                                    type="danger"
                                    effect="light"
                                    round
                                >
                                    失败
                                </el-tag>
                            </span>
                        </div>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <g-pagination
            :current-page="logParam.page.currentPage"
            :page-size="logParam.page.pageSize"
            :total="logParam.page.totalCount"
            @current-change="changePageFunc"
            @size-change="changeSizeFunc"
        />
    </g-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import type { TableHeadList } from '@/types/storeModule'
import router from '@/router'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Loading } from '@/components/Dialog/types'
import { deleteJobApi, changeStatusApi, runApi, getJobLogApi } from '@/api/monitor'
import { assign } from 'lodash-es'

const logVisible = ref<boolean>(false)
const logTitle = ref<string>('false')


const storeModelName = 'monitorJobModule'
const getTableList = () => {
    store.dispatch('data/getTableData', storeModelName)
}
const tableOperation = {
    width: 180,
    fixed: 'right',
    buttonGroups: [
        () => {
            return {
                name: '编辑',
                isShow: true,
                click: ({ row }) => {
                    router.push({
                        path: '/monitor/job/edit',
                        query: { jobId: row.jobId }
                    })
                }
            }
        },
        () => {
            return {
                name: '删除',
                type: 'danger',
                isShow: true,
                click: ({ row }) => {
                    if (row.runing === '1') {
                        ElMessageBox.confirm('确认删除吗？', '提示', {
                            type: 'warning'
                        }).then(() => {
                            deleteJobApi(row.jobId).then((res) => {
                                if (res.code * 1 === 200) {
                                    ElMessage.success('删除成功')
                                    setTimeout(() => {
                                        getTableList()
                                    }, 100)
                                }
                            })
                        })
                    } else {
                        ElMessage.warning('任务运行中，无法删除')
                    }
                }
            }
        },
        () => {
            return {
                name: '执行',
                type: 'success',
                isShow: true,
                click: ({ row }) => {
                    if (row.runing === '1') {
                        ElMessage.warning('任务已停用，无法执行')
                    } else {
                        ElMessageBox.confirm('确认执行吗？', '提示', {
                            type: 'warning'
                        }).then(() => {
                            runApi(row).then((res) => {
                                if (res.code * 1 === 200) {
                                    ElMessage.success('执行成功')
                                }
                            })
                        })
                    }
                }
            }
        },
        () => {
            return {
                name: '调度日志',
                type: 'info',
                isShow: true,
                click: ({ row }) => {
                    logVisible.value = true
                    logTitle.value = `『${row.jobName}』调度日志`
                    logParam.value.entity = { jobName: row.jobName, jobGroup: row.jobGroup }
                    getLogDataFunc(logParam.value)
                }
            }
        }
    ]
}

const tableHeadListSlotName = computed(() => {
    const tableHeadList = store.state[storeModelName].tableHeadList
    return tableHeadList.filter((item: TableHeadList) => item.slotName)
})
const changeStatusFunc = (row: any) => {
    if(row.jobId){
        changeStatusApi({ jobId: row.jobId, runing: row.runing }).then((res) => {
            if (res.code * 1 === 200) {
                ElMessage.success(row.runing === '1' ? '切换为已停用' : '切换为运行中')
                setTimeout(() => {
                    getTableList()
                }, 100)
            }
        })
    }
}
// 日志相关
const logTableHeadList = store.state[storeModelName].logTableHeadList
const logData = ref([])
interface logParamInterface {
    page: {
        currentPage: number
        pageSize: number
        totalCount: number
        totalPage: number
        sortField: string
        order: string
    }
    entity: {
        jobName: string
        jobGroup: string
    }
}
const logParam = ref<logParamInterface>({
    page: {
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
        totalPage: 0,
        sortField: 'create_time',
        order: 'desc'
    },
    entity:{
        jobName: '',
        jobGroup: ''
    }
})
const getLogDataFunc = (param: any) => {
    getJobLogApi(param).then((res) => {
        console.log(res)
        logData.value = res?.result
        assign(logParam.value, {
            page: {
                currentPage: res.currentPage,
                pageSize: res.pageSize,
                totalCount: res.totalCount,
                totalPage: res.totalPage,
                sortField: res.sortField,
                desc: res.desc
            }
        })
    })
}
const changePageFunc = (current: number) => {
    logParam.value.page.currentPage = current
    getLogDataFunc(logParam.value)
}
const changeSizeFunc = (size: any) => {
    logParam.value.page.pageSize = size
    getLogDataFunc(logParam.value)
}
</script>
